from tool.repo_info import get_org_repo_name_list
from tool.utils_config import get_repo_setting_dict_from_config, get_access_token_from_config, \
    get_repos_no_setting_from_config
from tool.utils_net import request_patch, is_token_valid


def assemble_setting_dict_with_necessary_info(repo_setting_dict, repo_name):
    access_token = get_access_token_from_config()
    assert is_token_valid(access_token), '请于config.toml, 配置有效的access_token'
    repo_setting_dict['access_token'] = access_token
    repo_setting_dict['name'] = repo_name


def modify_org_repos_func_setting(organization, repo_setting_dict=None, repo_filter=None):
    if not repo_setting_dict:
        repo_setting_dict = get_repo_setting_dict_from_config()
    repo_list_need_to_modify = list(filter(repo_filter, get_org_repo_name_list(organization)))
    for idx, repo_name in enumerate(repo_list_need_to_modify):
        assemble_setting_dict_with_necessary_info(repo_setting_dict, repo_name)
        modify_repo_func_setting(organization, repo_name, repo_setting_dict=repo_setting_dict)


def modify_repo_func_setting(owner, repo_name, repo_path=None, repo_setting_dict=None):
    if repo_path is None:
        repo_path = repo_name
    if not repo_setting_dict:
        repo_setting_dict = get_repo_setting_dict_from_config()
        assemble_setting_dict_with_necessary_info(repo_setting_dict, repo_name)
    open_api = f'https://gitee.com/api/v5/repos/{owner}/{repo_path}'
    response = request_patch(open_api, repo_setting_dict)
    if response.status_code == 200:
        print(f'{owner}的{repo_name}仓，设置修改成功')
    else:
        print(f'{owner}的{repo_name}仓，修改失败，{response.reason}')


def is_repo_need_to_modify(repo_to_check):
    repos_no_need_to_set = get_repos_no_setting_from_config()
    for repo_name in repos_no_need_to_set:
        if repo_name in repo_to_check:
            print(f'根据配置信息config.toml, {repo_to_check}仓，无需修改，已跳过')
            return False
    return True


if __name__ == '__main__':
    # 根据组织名和仓库名，修改单仓设置
    # 设置修改为配置文件config.toml中repo_setting的信息
    modify_repo_func_setting('openharmony', 'docs')

    # 根据组织名，修改组织下仓库设置
    # 设置修改为配置文件config.toml中repo_setting的信息
    # 设置项：在配置文件config.toml中repo_no_need_to_change_setting项，配置无需修改的仓库名
    modify_org_repos_func_setting('openharmony', repo_filter=is_repo_need_to_modify)
